<template>
  <div
    class="d-flex flex-column justify-content-start overflow-hidden page-wrapper"
  >
    <JoinApplicationPhaseStepper />
    <b-form style="margin-top: 19px;">
      <div v-if="currentStep === 0" style="width: 100%;">
        <div class="form-segment">
          <p class="form-segment-title">基本资料</p>
          <div class="form-line">
            <label for="companyName">* 公司名称:</label>
            <b-input
              id="companyName"
              v-model="$v.formPart0.companyName.$model"
              class="mr-sm-2 mb-sm-0"
              :state="
                $v.formPart0.companyName.$dirty
                  ? !$v.formPart0.companyName.$error
                  : null
              "
            />
          </div>
          <div class="form-line">
            <label for="companyAddress">* 公司地址:</label>
            <b-input
              id="companyAddress"
              v-model="$v.formPart0.companyAddress.$model"
              class="mr-sm-2 mb-sm-0"
              :state="
                $v.formPart0.companyAddress.$dirty
                  ? !$v.formPart0.companyAddress.$error
                  : null
              "
            />
          </div>
          <div class="form-line">
            <label for="bizCategory">* 主营类目:</label>
            <b-input
              id="bizCategory"
              v-model="$v.formPart0.bizCategory.$model"
              class="mr-sm-2 mb-sm-0"
              :state="
                $v.formPart0.bizCategory.$dirty
                  ? !$v.formPart0.bizCategory.$error
                  : null
              "
            />
          </div>
        </div>
      </div>
      <div v-if="currentStep === 1" style="width: 100%;">
        <div class="form-segment">
          <p class="form-segment-title">1. 法人信息</p>
          <div class="form-line">
            <label for="legalRepresentativeName">* 法人姓名:</label>
            <b-input
              id="legalRepresentativeName"
              v-model="$v.formPart1.legalRepresentativeName.$model"
              class="mr-sm-2 mb-sm-0"
              :state="
                $v.formPart1.legalRepresentativeName.$dirty
                  ? !$v.formPart1.legalRepresentativeName.$error
                  : null
              "
            />
          </div>
          <div class="form-line">
            <label for="legalRepresentativeIdAccount">* 法人身份证号:</label>
            <b-input
              id="legalRepresentativeIdAccount"
              v-model="$v.formPart1.legalRepresentativeIdAccount.$model"
              class="mr-sm-2 mb-sm-0"
              :state="
                $v.formPart1.legalRepresentativeIdAccount.$dirty
                  ? !$v.formPart1.legalRepresentativeIdAccount.$error
                  : null
              "
            />
          </div>
          <div class="form-line-uploader">
            <label for="idAccount">* 法人手持身份证照:</label>
            <div class="form-line-uploader-group">
              <a-upload
                :name="$options.imageUploadField"
                :action="$options.imageUploadAPI"
                list-type="picture"
                :file-list="uploader.legalRepresentativeIdPhotoFront"
                :before-upload="
                  beforeUpload.bind(
                    null,
                    'formPart1.legalRepresentativeIdPhotoFront'
                  )
                "
                :remove="uploadedImageRemoving"
                :class="{
                  'is-invalid':
                    $v.formPart1.legalRepresentativeIdPhotoFront.$error,
                }"
                @change="onUploaderStatusChanged"
              >
                <a-button><a-icon type="upload" />正面</a-button>
              </a-upload>
              <a-upload
                :name="$options.imageUploadField"
                :action="$options.imageUploadAPI"
                list-type="picture"
                :file-list="uploader.legalRepresentativeIdPhotoRear"
                :before-upload="
                  beforeUpload.bind(
                    null,
                    'formPart1.legalRepresentativeIdPhotoRear'
                  )
                "
                :remove="uploadedImageRemoving"
                :class="{
                  'is-invalid':
                    $v.formPart1.legalRepresentativeIdPhotoRear.$error,
                }"
                @change="onUploaderStatusChanged"
              >
                <a-button><a-icon type="upload" />背面</a-button>
              </a-upload>
            </div>
          </div>
          <div class="form-line">
            <label for="tel">* 法人电话:</label>
            <b-input
              id="tel"
              v-model="$v.formPart1.legalRepresentativeTel.$model"
              class="mr-sm-2 mb-sm-0"
              :state="
                $v.formPart1.legalRepresentativeTel.$dirty
                  ? !$v.formPart1.legalRepresentativeTel.$error
                  : null
              "
            />
          </div>
        </div>
        <div class="form-segment" style="margin-top: 19px;">
          <p class="form-segment-title">2. 企业信息</p>
          <div class="form-line-uploader">
            <label for="bizLicense">* 营业执照:</label>
            <div class="form-line-uploader-group">
              <a-upload
                :name="$options.imageUploadField"
                :action="$options.imageUploadAPI"
                list-type="picture"
                :file-list="uploader.bizLicense"
                :before-upload="beforeUpload.bind(null, 'formPart1.bizLicense')"
                :remove="uploadedImageRemoving"
                :class="{ 'is-invalid': $v.formPart1.bizLicense.$error }"
                @change="onUploaderStatusChanged"
              >
                <a-button><a-icon type="upload" />上传</a-button>
              </a-upload>
              <a-button class="form-line-uploader-group-placeholder">
                <a-icon type="upload" />上传
              </a-button>
            </div>
          </div>
          <div class="form-line">
            <label for="companyCode">统一社会信用代码:</label>
            <b-input
              id="companyCode"
              v-model="formPart1.companyCode"
              class="mr-sm-2 mb-sm-0"
            />
          </div>
          <div class="form-line">
            <label for="companyBankAccount">* 对公账户:</label>
            <b-input
              id="companyBankAccount"
              v-model="$v.formPart1.companyBankAccount.$model"
              class="mr-sm-2 mb-sm-0"
              :state="
                $v.formPart1.companyBankAccount.$dirty
                  ? !$v.formPart1.companyBankAccount.$error
                  : null
              "
            />
          </div>
          <div class="form-line-uploader">
            <label for="bankPermits">开户许可证:</label>
            <div class="form-line-uploader-group">
              <a-upload
                :name="$options.imageUploadField"
                :action="$options.imageUploadAPI"
                list-type="picture"
                :file-list="uploader.bankPermits"
                :before-upload="
                  beforeUpload.bind(null, 'formPart1.bankPermits')
                "
                :remove="uploadedImageRemoving"
                @change="onUploaderStatusChanged"
              >
                <a-button><a-icon type="upload" />上传</a-button>
              </a-upload>
              <a-button class="form-line-uploader-group-placeholder">
                <a-icon type="upload" />上传
              </a-button>
            </div>
          </div>
        </div>
        <div class="form-segment" style="margin-top: 19px;">
          <p class="form-segment-title">3. 管理人信息</p>
          <div class="form-line">
            <label for="managerUsername">店铺管理人姓名:</label>
            <b-input
              id="managerUsername"
              v-model="formPart1.managerUsername"
              class="mr-sm-2 mb-sm-0"
            />
          </div>
          <div class="form-line">
            <label for="managerTel">店铺管理人电话:</label>
            <b-input
              id="managerTel"
              v-model="formPart1.managerTel"
              class="mr-sm-2 mb-sm-0"
            />
          </div>
          <div class="form-line-uploader">
            <label for="idPhotoAdmin">管理人手持身份证照:</label>
            <div class="form-line-uploader-group">
              <a-upload
                :name="$options.imageUploadField"
                :action="$options.imageUploadAPI"
                list-type="picture"
                :file-list="uploader.idPhotoFrontAdmin"
                :before-upload="
                  beforeUpload.bind(null, 'formPart1.idPhotoFrontAdmin')
                "
                :remove="uploadedImageRemoving"
                @change="onUploaderStatusChanged"
              >
                <a-button><a-icon type="upload" />正面</a-button>
              </a-upload>
              <a-upload
                :name="$options.imageUploadField"
                :action="$options.imageUploadAPI"
                list-type="picture"
                :file-list="uploader.idPhotoRearAdmin"
                :before-upload="
                  beforeUpload.bind(null, 'formPart1.idPhotoRearAdmin')
                "
                :remove="uploadedImageRemoving"
                @change="onUploaderStatusChanged"
              >
                <a-button><a-icon type="upload" />背面</a-button>
              </a-upload>
            </div>
          </div>
        </div>
      </div>
      <div v-if="currentStep === 2" style="width: 100%;">
        <div class="form-segment">
          <p class="form-segment-title">品牌信息</p>
          <div class="form-line force-inline">
            <label for="trademarkType">品牌商标类型:</label>
            <div class="form-line-radio-group">
              <b-form-radio-group
                v-model="formPart2.trademarkType"
                button-variant="outline-secondary"
                buttons
              >
                <b-form-radio value="0">自有</b-form-radio>
                <b-form-radio value="1">授权</b-form-radio>
              </b-form-radio-group>
            </div>
          </div>
          <div class="form-line">
            <label for="trademarkRegistrationNo">品牌商标注册号:</label>
            <b-input
              id="trademarkRegistrationNo"
              v-model="formPart2.trademarkRegistrationNo"
              class="mr-sm-2 mb-sm-0"
            />
          </div>
          <div class="form-line-uploader">
            <label for="trademarkRegistrationCert">品牌商标注册证明:</label>
            <div class="form-line-uploader-group">
              <a-upload
                :name="$options.imageUploadField"
                :action="$options.imageUploadAPI"
                list-type="picture"
                :file-list="uploader.trademarkRegistrationCert"
                :before-upload="
                  beforeUpload.bind(null, 'formPart2.trademarkRegistrationCert')
                "
                :remove="uploadedImageRemoving"
                @change="onUploaderStatusChanged"
              >
                <a-button><a-icon type="upload" />上传</a-button>
              </a-upload>
              <a-button class="form-line-uploader-group-placeholder">
                <a-icon type="upload" />上传
              </a-button>
            </div>
          </div>
          <div class="form-line force-inline">
            <label for="trademarkRegistrationCertValidityPeriod">
              注册证明有效期:
            </label>
            <a-date-picker
              v-model="formPart2.trademarkRegistrationCertValidityPeriod"
              placeholder="请选择"
            />
          </div>
          <div class="form-line-uploader">
            <label for="trademarkAuthorizationCert">品牌商标授权证明:</label>
            <div class="form-line-uploader-group">
              <a-upload
                :name="$options.imageUploadField"
                :action="$options.imageUploadAPI"
                list-type="picture"
                :file-list="uploader.trademarkAuthorizationCert"
                :before-upload="
                  beforeUpload.bind(
                    null,
                    'formPart2.trademarkAuthorizationCert'
                  )
                "
                :remove="uploadedImageRemoving"
                @change="onUploaderStatusChanged"
              >
                <a-button><a-icon type="upload" />上传</a-button>
              </a-upload>
              <a-button class="form-line-uploader-group-placeholder">
                <a-icon type="upload" />上传
              </a-button>
            </div>
          </div>
          <div class="form-line force-inline">
            <label for="trademarkAuthorizationValidityPeriod">
              授权证明有效期:
            </label>
            <a-date-picker
              v-model="formPart2.trademarkAuthorizationValidityPeriod"
              placeholder="请选择"
            />
          </div>
        </div>
      </div>
      <div class="form-btn">
        <b-button
          variant="outlinesecondary"
          pill
          :disabled="submittingForm"
          @click="onSubmit"
        >
          {{ submitButtonText }}
        </b-button>
      </div>
    </b-form>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
import { RECORD_SHOP_APPLICATION_AGREEMENT_SOURCE } from '@/assets/constants/mutations/';
import JoinApplicationPhaseStepper from '@/components/m/JoinApplicationPhaseStepper';
import { required } from 'vuelidate/lib/validators';
import siteConfig from '@/assets/config/site';

const UPLOADER_FIELD_ID_NAME_MAPPING = {
  legalRepresentativeIdPhotoFront: '法人手持身份证照(正面)',
  legalRepresentativeIdPhotoRear: '法人手持身份证照(背面)',
  bizLicense: '营业执照',
  bankPermits: '开户许可证',
  idPhotoFrontAdmin: '管理人手持身份证照(正面)',
  idPhotoRearAdmin: '管理人手持身份证照(背面)',
  trademarkRegistrationCert: '品牌商标注册证明',
  trademarkAuthorizationCert: '品牌商标授权证明',
};

export default {
  imageUploadAPI: `${siteConfig.apiPrefix}${siteConfig.assetsUploadAPI}`,
  imageUploadField: siteConfig.assetsUploadField,
  enterpriseJoinApplicationAPI: `${siteConfig.apiPrefix}${siteConfig.enterpriseJoinApplicationAPI}`,
  components: {
    JoinApplicationPhaseStepper,
  },
  layout: 'staticBanner',
  head() {
    return {
      title: '企业/公司入驻申请',
    };
  },
  data() {
    return {
      currentStep: 0,
      submittingForm: false,
      formPart0: {
        companyName: null,
        companyAddress: null,
        bizCategory: null,
      },
      formPart1: {
        legalRepresentativeName: null,
        legalRepresentativeIdAccount: null,
        legalRepresentativeIdPhotoFront: null,
        legalRepresentativeIdPhotoRear: null,
        legalRepresentativeTel: null,
        bizLicense: null,
        companyCode: null,
        companyBankAccount: null,
        bankPermits: null,
        managerUsername: null,
        managerTel: null,
        idPhotoFrontAdmin: null,
        idPhotoRearAdmin: null,
      },
      formPart2: {
        trademarkType: 1,
        trademarkRegistrationNo: null,
        trademarkRegistrationCert: null,
        trademarkRegistrationCertValidityPeriod: null,
        trademarkAuthorizationCert: null,
        trademarkAuthorizationValidityPeriod: null,
      },
      uploader: {
        legalRepresentativeIdPhotoFront: [],
        legalRepresentativeIdPhotoRear: [],
        bizLicense: [],
        bankPermits: [],
        idPhotoFrontAdmin: [],
        idPhotoRearAdmin: [],
        trademarkRegistrationCert: [],
        trademarkAuthorizationCert: [],
      },
    };
  },
  computed: {
    isFinalStep() {
      return this.currentStep === 2;
    },
    submitButtonText() {
      if (this.isFinalStep) {
        return '确认提交';
      } else {
        return '下一步';
      }
    },
    ...mapState(['shopApplicationAgreementAccepted']),
  },
  mounted() {
    if (!this.shopApplicationAgreementAccepted) {
      this.recordAgreementSource('enterprise');
      this.$router.replace('/agreement');
    }
  },
  methods: {
    async onSubmit() {
      this.$v[`formPart${this.currentStep}`].$touch();
      if (this.$v[`formPart${this.currentStep}`].$invalid) {
        this.$message.error('请填入必填项');
        return;
      }
      if (this.currentStep < 2) {
        this.currentStep++;
        return;
      }
      const formData = {
        ...this.formPart0,
        ...this.formPart1,
        ...this.formPart2,
      };
      // console.log('>>>>payload:', JSON.stringify(formData));
      this.submittingForm = true;
      try {
        await this.$axios.$post(
          this.$options.enterpriseJoinApplicationAPI,
          formData
        );
        this.resetForm();
        this.submittingForm = false;
        this.$router.replace('/application/submitted');
      } catch (err) {
        this.submittingForm = false;
        if (err.response && err.response.data && err.response.data.msg) {
          this.$message.error(err.response.data.msg);
        } else {
          this.$message.error('网络错误，请稍后再试');
        }
      }
    },
    resetForm() {
      this.$v.$reset();
      this.formPart0 = {
        companyName: null,
        companyAddress: null,
        bizCategory: null,
      };
      this.formPart1 = {
        legalRepresentativeName: null,
        legalRepresentativeIdAccount: null,
        legalRepresentativeIdPhotoFront: null,
        legalRepresentativeIdPhotoRear: null,
        legalRepresentativeTel: null,
        bizLicense: null,
        companyCode: null,
        companyBankAccount: null,
        bankPermits: null,
        managerUsername: null,
        managerTel: null,
        idPhotoFrontAdmin: null,
        idPhotoRearAdmin: null,
      };
      this.formPart2 = {
        trademarkType: 1,
        trademarkRegistrationNo: null,
        trademarkRegistrationCert: null,
        trademarkRegistrationCertValidityPeriod: null,
        trademarkAuthorizationCert: null,
        trademarkAuthorizationValidityPeriod: null,
      };
      this.uploader = {
        legalRepresentativeIdPhotoFront: [],
        legalRepresentativeIdPhotoRear: [],
        bizLicense: [],
        bankPermits: [],
        idPhotoFrontAdmin: [],
        idPhotoRearAdmin: [],
        trademarkRegistrationCert: [],
        trademarkAuthorizationCert: [],
      };
    },
    beforeUpload(targetField, file) {
      file.targetField = targetField;
      return true;
    },
    uploadedImageRemoving(file) {
      const [formField, targetField] = file.targetField.split('.');
      this[formField][targetField] = null;
      if (this.$v[formField] && this.$v[formField][targetField]) {
        this.$v[formField][targetField].$touch();
      }
      console.log(this.$v[formField][targetField].$error);
      return true;
    },
    onUploaderStatusChanged(info) {
      const { file, fileList } = info;
      const [formField, targetField] = file.targetField.split('.');
      const targetName = UPLOADER_FIELD_ID_NAME_MAPPING[targetField] || '图片';
      if (file.status === 'error') {
        this.$message.error(`上传${targetName}失败，请稍后再试`);
        this.uploader[targetField] = fileList.slice(0, -1);
        return;
      }
      if (file.status === 'done') {
        let imgPath = null;
        try {
          imgPath = file.response.data.url;
        } catch {
          imgPath = null;
        }
        if (!imgPath) {
          this.$message.error(`上传${targetName}失败，请稍后再试`);
          return;
        }
        this.$message.success(`上传${targetName}成功`);
        this[formField][targetField] = imgPath;
        if (this.$v[formField] && this.$v[formField][targetField]) {
          this.$v[formField][targetField].$touch();
        }
      }
      this.uploader[targetField] = fileList.slice(-1);
    },
    ...mapMutations({
      recordAgreementSource: RECORD_SHOP_APPLICATION_AGREEMENT_SOURCE,
    }),
  },
  validations: {
    formPart0: {
      companyName: {
        required,
      },
      companyAddress: {
        required,
      },
      bizCategory: {
        required,
      },
    },
    formPart1: {
      legalRepresentativeName: {
        required,
      },
      legalRepresentativeIdAccount: {
        required,
      },
      legalRepresentativeIdPhotoFront: {
        required,
      },
      legalRepresentativeIdPhotoRear: {
        required,
      },
      legalRepresentativeTel: {
        required,
      },
      bizLicense: {
        required,
      },
      companyBankAccount: {
        required,
      },
    },
    formPart2: {},
  },
};
</script>

<style lang="scss" scoped>
$inline-control-padding-left: 24px;
$inline-control-padding-right: 12px;

.page-wrapper {
  height: 100%;
  background-color: #f3f3f3;
  @include media-breakpoint-up(sm) {
    padding-top: $main-nav-bar-height;
  }
}
form {
  font-size: 13px;
  line-height: 18px;
  letter-spacing: 0.27px;
  text-align: right;
  max-width: 420px;
  width: 100%;
  align-self: center;
  @include media-breakpoint-down(xs) {
    padding-left: 24px;
    padding-right: 24px;
  }
}
.form-line {
  width: 100%;
  font-family: 'PingFangSC-Regular', 'PingFang SC';
  font-size: 13px;
  line-height: 20px;
  color: #4a4a4a;
  letter-spacing: 0.27px;
  display: flex;
  @include media-breakpoint-down(xs) {
    height: 36px;
    align-items: center;
    label {
      flex: 0 0 124px;
      margin-bottom: 0px;
      text-align: right;
    }
    input {
      flex: 1 1 auto;
      border-color: transparent;
      font-family: 'PingFangSC-Regular', 'PingFang SC';
      font-size: 13px;
      line-height: 18px;
      letter-spacing: 0.27px;
      margin-left: 0.5rem;
      padding-left: 0.5rem;
      background-color: #f3f3f3;
    }
    input.is-invalid {
      border-color: #dc3545;
      box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
    }
  }
  @include media-breakpoint-up(sm) {
    flex-direction: column;
    align-items: flex-start;
    margin: 0.5rem 0px 1.5rem 24px;
    text-align: left;
    &.force-inline {
      flex-direction: row;
      align-items: center;
      label {
        flex: 0 0 124px;
        margin-bottom: 0px;
      }
    }
  }
  .ant-calendar-picker {
    width: 100%;
    margin-left: $inline-control-padding-left;
  }
  ::v-deep .ant-calendar-picker-input {
    font-family: 'PingFangSC-Regular', 'PingFang SC';
    font-size: 13px;
    line-height: 18px;
    letter-spacing: 0.27px;
  }
}
.form-line-uploader {
  width: 100%;
  min-height: 36px;
  display: flex;
  align-items: flex-start;
  font-family: 'PingFangSC-Regular', 'PingFang SC';
  font-size: 13px;
  line-height: 20px;
  color: #4a4a4a;
  letter-spacing: 0.27px;
  @include media-breakpoint-down(xs) {
    text-align: right;
  }
  @include media-breakpoint-up(sm) {
    text-align: left;
    margin-left: 24px;
    margin: 0.5rem 0px 1.5rem 24px;
  }
  label {
    flex: 0 0 124px;
    margin-bottom: 0px;
    line-height: 36px;
  }
  // input {
  //   flex: 1 1 auto;
  //   border-color: transparent;
  // }
}
.form-line-buttons {
  width: 100%;
  text-align: left;
  span {
    margin-left: 30px;
  }
}
.form-line-uploader-group {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding-left: $inline-control-padding-left;
  padding-right: $inline-control-padding-right;
  ::v-deep .ant-upload-select-picture {
    width: 100%;
    text-align: center;
    line-height: 36px;
  }
  ::v-deep .is-invalid {
    .ant-btn {
      border-color: #dc3545;
    }
  }
  ::v-deep .ant-upload-btn {
    line-height: 36px;
    font-size: 13px;
    letter-spacing: 0.27px;
    .ant-btn {
      height: 32px;
      line-height: 30px;
      font-size: 13px;
      letter-spacing: 0.27px;
      padding: 0 12px;
    }
    i.anticon {
      vertical-align: baseline;
    }
  }
  ::v-deep .ant-upload-list-item {
    margin-top: 0px;
    margin-bottom: 8px;
    .anticon-close {
      font-size: 14px;
      top: 2px;
      right: 2px;
    }
  }
  ::v-deep .ant-upload-list-item-name {
    display: none;
  }
  ::v-deep .ant-upload-list-item-thumbnail {
    position: static;
  }
}
.form-line-uploader-group-placeholder {
  visibility: hidden;
}
.form-line-radio-group {
  width: 100%;
  .btn-group {
    display: flex;
    justify-content: space-between;
    padding-left: $inline-control-padding-left;
    padding-right: $inline-control-padding-right;
  }
  label {
    line-height: 30px;
    font-size: 13px;
    letter-spacing: 0.27px;
    display: inline-block;
    flex: unset !important;
    padding: 0 12px;
    border-top-right-radius: 4px !important;
    border-bottom-right-radius: 4px !important;
    border-top-left-radius: 4px !important;
    border-bottom-left-radius: 4px !important;
    border: 1px solid rgb(217, 217, 217);
    border-radius: 4px;
    box-shadow: 0 2px 0 rgba(0, 0, 0, 0.015);
  }
}
.form-segment {
  width: 100%;
  // @include make-col-ready();
  // padding-left: 29px;
  // @include media-breakpoint-up(sm) {
  //   padding-left: 0px;
  //   width: percentage(8 / 12);
  // }
  // @include media-breakpoint-up(md) {
  //   width: percentage(6 / 12);
  // }
  // @include media-breakpoint-up(lg) {
  //   width: percentage(4 / 12);
  // }
}
.form-segment-title {
  font-family: PingFangSC-Semibold;
  font-size: 14px;
  line-height: 20px;
  letter-spacing: 0.29px;
  margin: 0px;
  text-align: left;
}
.form-btn {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  button {
    max-width: 420px;
    width: 100%;
    height: 50px;
    font-size: 14px;
    color: #4a4a4a;
    line-height: 20px;
    letter-spacing: 0.5px;
    background: #fff;
    box-shadow: 0 1px 8px -2px rgba(0, 0, 0, 0.5);
    margin: 30px 30px 20px;
  }
}
</style>
